var pGrid, pGridData, opt, picking_id, udata;
$(function() {
	   
	  

	$("#layout_main").ligerLayout({
		bottomHeight : "46%",
		allowBottomResize : false
	});

	$("form").ligerForm();

	$("#d-menu").ligerToolBar({items:[
	              				    {text:'保存',click:toSave,icon:'save'},
	              					{line:true},
	              					{text:'返回',click:toBack,icon:'back'},
	              				    {line:true},
	              				    {text:'清空',click:resetArea,icon:'clear'},
	              					{line:true}
	              				]});
	
	$('#myTab li:eq(1) a').tab('show');
	
	// 明细列表设置
   	pGrid = $("#p-div").ligerGrid({
        columns:[
//			{display:'ID',name:'id',width:90},	
			{display:'产品',name:'name',width:100,editor:{type:'popup',onButtonClick:selectProduct}},
			{display:'内部货号',name:'code',width:100,textField:'code',valueField:'code'}, 
            {display:'规格属性',name:'prod_att',width:160},
            {display:'数量',name:'specs',width:60},
            {display:'目的库位',name:'location',width:100},
            {display:'状态',name:'specs',width:90},
//            
//            {display:'单位',name:'product_uom',width:60,render:function(item){return paramRender(item,'uom',item.product_uom);}},
//            {display:'品牌',name:'brand',width:80,render:function(item){return paramRender(item,'brand',item.brand);},editor:{type:'select',data:getData('Brand'),valueField:'value',textField:'name'}},
//            {display:'采购数量',name:'tar_product_qty',align:'right',editor:{type:'string'},render:function(item){return item.tar_product_qty ? parseFloat(item.tar_product_qty).toFixed(2) : '';}},
//            {display:'入库数量',name:'product_qty',id:'num',align:'right',editor:{type:'string'},render:function(item){return item.product_qty ? parseFloat(item.product_qty).toFixed(2) : '';}},
//            {display:'采购单价',name:'source_price_unit',align:'right',editor:{type:'string'},render:function(item){return item.source_price_unit ? parseFloat(item.source_price_unit).toFixed(2) : '';}},
//            {display:'入库单价',name:'price_unit',id:'price',align:'right',editor:{type:'string'},render:function(item){return item.price_unit ? parseFloat(item.price_unit).toFixed(2) : '';}},
//            {display:'金额',name:'total',id:'total',align:'right',render:calcTotal},
            
        ], 
        pageSize:20, 
        width:'99%',
        height:'40%', 
        rownumbers:true,
        fixedCellHeight:false, 
        enabledEdit:true, 
        onSelectRow:function(rowdata, rowindex){$("#txtrowindex").val(rowindex);},
        param_partner:'partner_list'
	});
	//明细新增按钮
	appendAddBtn(function(){
		pGrid.addEditRow();
			$(".l-grid2 .l-grid-body-inner").attr("style", "");
	}, "添加商品明细");
	//明细删除按钮
	appendDeleteBtn(deleteRow, "删除商品明细");
	//解析URL传递的参数
	var query = getQueryString(window.location.toString());
	opt = query.o;

	if (opt) {
		picking_id = query.picking_id;
		if (opt === 'm') {
			ajaxSubmitGet("/stock/searchStock/" + picking_id, function(data) {
				//绑定数据
				bindVal(data);
			});
		}
	} else {
		// 附初始值
		// 					ajaxSubmit("/cm/rbac/cmUser.do?method=getUserInfo", null, function(data) {
		// 						$('#deptS').val(data['oname']);
		// 						$('#deptCodeS').val(data['oid']);
		// 						$('#createUserS').val(data['uname']);
		// 						$('#createUserCodeS').val(data['uid']);
		// 						$("#createDateS").val(data['date']);
		// 						$("#WriteDateS").val(data['date']);
		// 					}, null, false);
	}

	udata = getData('user', {
		orgid : $("#deptCodeS").val()
	}, false);

	var moveInBox = $("#moveInS").ligerComboBox({
		autocomplete : true,
		valueField : 'value',
		textField : 'name',
		data : udata,
		onSelected : function(v, t) {
			$("#moveInIdS").val(v);
		}
	});

	var get_warehose_list = new function() {
		return getData('base_point');
	}
	$("#warehouseInS").ligerComboBox({
		autocomplete : true,
		valueField : 'value',
		textField : 'name',
		data : get_warehose_list,
		onSelected : function(v, t) {
			$("#warehouseS").val(v);
		}
	});

	var get_partner_list = new function() {
		return getData('partner_list');
	}
	$("#partnerInS").ligerComboBox({
		autocomplete : true,
		valueField : 'value',
		textField : 'name',
		data : get_partner_list,
		onSelected : function(v, t) {
			$("#partnerS").val(v);
		}
	});

	$("#pageloading").hide();
	
	 
	
});
function bindVal(data) {
	data = data['data'];
	//绑定主表数据 
	$('#codeS').val(data.code);
	$('#codeS').val(data.code);
	$('#originS').val(data.origin);
	$('#partnerInS').val(paramRender(null, 'partner_list', data.partner_id));
	$('#partnerS').val(data.partner_id);
	$('#predDateS').val(data.min_date);
	//$('#warehouseInS').val(paramRender(null,'base_point',data.warehose_id));
	//$('#warehouseS').val(data.warehose_id);
	//$('#moveInS').val(paramRender(null,'user',data.move_in_user));
	//$('#moveInIdS').val(data.move_in_user);
	$('#noteS').val(data.note);
	$('#deptS').val(paramRender(null, 'org_list', data.dept_id));
	$('#deptCodeS').val(data.dept_id);
	$('#createUserS').val(paramRender(null, 'user', data.create_uid));
	$('#createUserCodeS').val(data.create_uid);
	$('#createDateS').val(data.create_date);

	//明细列表数据加载
	pGrid.setOptions({
		data : {
			Rows : data['items']
		}
	}); //设置数据参数
	pGrid.loadData();//加载数据 
}
// 产品明细选择
function selectProduct() {
	var selDialog = $.ligerDialog.open({
		height : 400,
		width : 650,
		isResize : true,
		url : '../select/product_select.html?o=s',
		title : '选择商品',
		buttons : [
				{
					text : '确定',
					onclick : function(item, dialog) {
						var data = dialog.frame.getSelectedRow();
						if (!data) {
							$.ligerDialog.warn('请选择商品!');
							return;
						}
						pGrid.endEdit();
						pGrid.updateCell('name', data.prod_temp_name, pGrid.getSelected());
						pGrid.updateCell('prod_att', data.prod_att, pGrid.getSelected());
						pGrid.updateCell('product_uom', data.uom, pGrid.getSelected());
						pGrid.updateCell('code', data.code, pGrid.getSelected());
						dialog.close();
					}
				}, {
					text : '取消',
					onclick : function(item, dialog) {
						dialog.close();
					}
				} ]
	});
	return false;
}

// 界面校验
function validate() {
	var valid = true;
	$('*[id$="S"],*[id$="S_txt"]').each(function(index, element) {
		if (!$(this).rules())
			return;
		if (!$(element).valid()) {
			valid = false;
			return;
		}
	});
	if (!valid)
		return false;

	if (pGrid.rows.length === 0) {
		$.ligerDialog.error('请添加入库商品。', '错误');
		return false;
	}

	var r, result;
	var i = 0;
	for (; i < pGrid.rows.length; i++) {
		r = pGrid.rows[i];
		// 					if (!r.code) {
		// 						result = '商品编号不能为空';
		// 						break;
		// 					}
		if (!r.tar_product_qty || parseInt(r.tar_product_qty) < 1) {
			result = '采购数量必须录入大于0的整数';
			break;
		}
		if (!r.product_qty || parseInt(r.product_qty) < 1) {
			result = '入库数量必须录入大于0的整数';
			break;
		}
		if (!r.source_price_unit || parseInt(r.source_price_unit) === 0.00001) {
			result = '采购单价必须录入大于0的数值';
			break;
		}
		if (!r.price_unit || parseInt(r.price_unit) === 0.00001) {
			result = '入库单价必须录入大于0的数值';
			break;
		}
		if (parseInt(r.tar_product_qty) < parseInt(r.product_qty)) {
			result = "入库数量不能大于采购数量，请修改入库数量";
			break;
		}
	}

	if (result) {
		$.ligerDialog.error('入库商品列表第[' + (++i)
				+ ']行存在错误<br/>原因：'.concat(result), '数据错误');
		return false;
	}
	return true;
}

// 保存处理方法 ，新增及修改 。
function toSave() {
	//单据校验
	if (!validate())
		return;
	var url;
	// 设置 主表数据
	var param = {
		origin : $("#originS").val(),
		partner_id : $("#partnerS").val(),
		min_date : $("#predDateS").val(),
		//warehose:$("#warehouseS").val(),
		//moveinuser:$("#moveInIdS").val(),
		note : $("#noteS").val()
	};
	if (opt === 'm') {
		// 进行修改数据库处理
		//处理主表数据
		param.code = $('#codeS').val();
		//修改人
		param.write_uid = $('#WriteUserCodeS').val();
		//修改日期
		param.write_date = $('#WriteDateS').val();

		param.__status = 'update';

		url = "/stock/updateStock";

	} else {
		// 新增时 数据处理
		param.__status = 'add'
		url = "/stock/saveStock";
		param.company_id = "0001";
		param.dept_id = "0001";
		//param.dept_id = $("#deptCodeS").val();
		//param.busiorg = "";
		//param.name = "";
		param.picking_type_id = "0";
		param.create_uid = $("#createUserCodeS").val();
		param.create_date = $("#createDateS").val();
		//param.movetype="01";
		param.state = "00";
		param.write_date = $('#WriteDateS').val();
	}
	// 设置 明细数据
	var items = pGrid.rows;
	param.items = items;
	// 提交后台保存数据转换为JSON 格式
	var data = JSON.stringify(param);
	//保存提交后台

	if (url)
		ajaxSubmit(url, data, function(data) {
			if (data['added']) {
				var picking = data['added'];
				picking_id = picking['id'];
			}
			if (parseInt(data['status']) > 0) {
				$.ligerDialog.success('保存成功', '操作完成', reloadPage);
			} else {
				$.ligerDialog.error('保存失败');
			}

		});

}
// 删除明细
function deleteRow() {
	var row = pGrid.getSelectedRow();
	if (!row) {
		$.ligerDialog.error('请先选择入库商品记录。', '错误');
		return;
	}
	$.ligerDialog.confirm('您确定要删除该项数据吗？', function(r) {
		if (!r)
			return;
		if (row.__status === 'add') {
			pGrid.deleteRow(row);
			if (pGrid.row && pGrid.row.length === 0)
				pGrid.data = {};
			return;
		}
		var param = new Object();
		param.id = row.id
		var data = JSON.stringify(reqObj('d', 'stock.delete.stock_move', JSON
				.stringify(param)));
		ajaxSubmit("/cm/rbac/cm.do?m=d", data, function(data) {
			if (data) {
				if (parseInt(data['status']) > 0) {
					$.ligerDialog.success('删除成功');
					pGrid.deleteRow(row);
				} else {
					$.ligerDialog.error('删除失败');
				}
			}
		});
	});
}

function calcTotal(item) {
	if (item.product_qty && item.price_unit) {
		return (parseFloat(item.product_qty) * parseFloat(item.price_unit))
				.toFixed(4);
	}
	return '0.0000';
}
// 界面重新载入
function reloadPage() {
	window.location = './stock_picking_detail.html?o=m&picking_id='
			.concat(picking_id);
}
//界面的返回处理，实际是关闭标签处理。
function toBack() {
	//关闭修改界面
	parent.tabManager.removeTabItem("modify_stockp");
	//关闭新增界面
	parent.tabManager.removeTabItem("new_stockp");
}
//清空表单
function resetArea() {
	toReset('#a_center input:not(.readonly),select,textarea');
}
